package option_log_service

import (
	"fmt"
	"peilian-api/app/global/common"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/model"

	"github.com/gin-gonic/gin"
)

// 获取筛选框的标签
func GetOptionS(ctx *gin.Context, typ uint) []string {
	fmt.Println(typ)
	if typ == 1 {
		return common.OneModule
	} else if typ == 2 {
		return common.TwoModule
	} else if typ == 3 {
		return common.OptionType
	}
	return make([]string, 0)
}

// 获取日志列表
func GetOptionLogList(ctx *gin.Context, ol model.OptionLogReq) ([]model.OptionLogResp, int64, error) {
	agentName := ol.AgentName
	page := ol.Page
	size := ol.Size
	oneModule := ol.OneModule
	twoModule := ol.TwoModule
	optionType := ol.OptionType
	query := ol.Query
	endTime := ol.EndTime
	startTime := ol.StartTime
	whereMap := make(map[string]interface{}, 0)
	if len(agentName) != 0 && agentName != "0" {
		whereMap["agent_name"] = agentName
	}
	if len(agentName) != 0 && oneModule != "0" {
		whereMap["one_module"] = oneModule
	}
	if len(agentName) != 0 && twoModule != "0" {
		whereMap["two_module"] = twoModule
	}
	if len(agentName) != 0 && optionType != "0" {
		whereMap["option_type"] = optionType
	}
	where := ""
	if len(startTime) != 0 && len(endTime) != 0 {
		where += fmt.Sprintf(" created_at > '%s' and created_at < '%s' ", startTime, endTime)
	}
	if len(query) != 0 {
		query = "%" + query + "%"
		if len(where) == 0 {
			where += fmt.Sprintf(" (user_name like '%s' or user_account like '%s') ", query, query)
		} else {
			where += fmt.Sprintf(" and (user_name like '%s' or user_account like '%s') ", query, query)
		}

	}

	// 结果返回
	var out []model.OptionLogResp
	logList, count, err := new(tables.OptionLog).GetOptionLogByWhere(whereMap, where, "id desc", int(page), int(size))
	if err != nil {
		return out, 0, err
	}
	for _, v := range logList {
		out = append(out, model.OptionLogResp{
			Id:          int64(v.ID),
			UserName:    v.UserName,
			AccountName: v.UserAccount,
			AgentName:   v.AgentName,
			OneModule:   v.OneModule,
			TwoModule:   v.TwoModule,
			OptionType:  v.OptionType,
			OptionNums:  v.Number,
			OptionTime:  v.CreatedAt.Format("2006-01-02 15:04:05"),
			IpAddress:   v.IpAddress,
		})
	}
	return out, count, nil
}
